package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import main.Terminal;
import model.Sale;
import model.Seat;
import model.ShowTime;
import model.Ticket;

public class DBTicket 
{
	private DBConnection con;
	private final String id = "ID";
	private final String seat = "SeatID";
	private final String showTime = "ShowTimeID";
	private final String sale = "SaleID"; 
	
	private final String selectAll = String.format("SELECT %s, %s, %s, %s FROM Ticket", id, seat, showTime, sale);
	
	public DBTicket()
	{
		con = DBConnection.getInstance();
	}
	
	public ArrayList<Ticket> findTickets(ShowTime s)
	{
		ArrayList<Ticket> result = new ArrayList<Ticket>();
		int showTimeID = new DBShowTime().getShowTimeID(s);
		
		
		String statement = selectWhere(String.format("%s = '%d'", showTime, showTimeID));
		ResultSet resSet = con.executeResSet(statement);
		
		try {
			while(resSet.next()) {
				
				int id = resSet.getInt(this.id);
				int seatId = resSet.getInt(this.seat);
				String saleID = resSet.getString(this.sale);
				
				Seat seat = new DBSeat().getSeat(seatId);
				result.add(new Ticket(id, seat, s, new DBSale().getSale(saleID, null)));
			}
		} catch (SQLException e) {
			Terminal.say("Could not retrieve result. \n Statement: " + statement, e);
		}
		
		return result;
	}
	
	private int getHighestId() {
		ResultSet resSet = con.executeResSet(String.format("SELECT %s FROM Ticket", id));
		
		int highestInt = -1;
		try {
			while(resSet.next()) {
				int id = resSet.getInt(this.id);
				if(id > highestInt) {
					highestInt = id;
				}
			}
		} catch (SQLException e) {
			Terminal.say("An Error occured while getting highest ID from Ticket.. ", e);
		}
		
		return highestInt;
	}

	public void addTicket(Seat seat, ShowTime s, Sale sale)
	{
		int id = getHighestId() + 1;
		con.execute(String.format("INSERT INTO Ticket VALUES ('%d', '%d', '%d', '%d')", id, seat.getId(), new DBShowTime().getShowTimeID(s), sale.getId()));
	}
	
	private String selectWhere(String param)
	{
		return selectAll +  " WHERE " + param;
	}
}
